package ru.arriah.servicedesk.web.client.action;

import java.io.IOException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;

public class LoginAction extends DumbAction {
   protected ClientManagerLocalHome clientManagerHome;

   public LoginAction() throws NamingException {
      super();

      clientManagerHome = 
         Utils.getClientManagerHomeInterface();
   }

   public String execute(ActionMapping actionMapping,
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
      try {
         ClientManagerLocalObject clientManager = 
            clientManagerHome.create();

         String login = request.getParameter("login");
         String password = request.getParameter("password");

         int clientId = clientManager.authorize(login, password);
         clientManager.remove();

         request.getSession().setAttribute("userId", clientId);
         request.getSession().setAttribute("role", "client");

         return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new LoginException("ErrorMessage.illegalLogin");
      }
   }
}